export const exportFileJSON = (data = {}, filename = "dataJSON.json") => {
  if (typeof data === "object") {
    data = JSON.stringify(data, null, 2); // 格式化成字符串
  }
  // 导出数据
  const blob = new Blob([data as string], { type: "text/json" }),
    e = new MouseEvent("click"),
    a = document.createElement("a");

  a.download = filename;
  a.href = window.URL.createObjectURL(blob);
  a.dataset.downloadurl = ["text/json", a.download, a.href].join(":");
  a.dispatchEvent(e);
};

/**
 * 导入数据的方法
 * @param {EventObject} 传入的参数为onchange的事件源event
 * @returns 返回为promise，then为数据，reject为报错信息
 */
export const importFileJSON = (ev: any) => {
  return new Promise((resolve, reject) => {
    const fileDom = ev.target,
      file = fileDom.files[0];

    // 格式判断
    if (file.type !== "application/json") {
      reject("仅允许上传json文件");
    }
    // 检验是否支持FileRender
    if (typeof FileReader === "undefined") {
      reject("当前浏览器不支持FileReader");
    }

    // 执行后清空input的值，防止下次选择同一个文件不会触发onchange事件
    ev.target.value = "";

    // 执行读取json数据操作
    const reader = new FileReader();
    reader.readAsText(file); // 读取的结果还有其他读取方式，我认为text最为方便

    reader.onerror = (err) => {
      reject( err || "json文件解析失败");
    };

    reader.onload = () => {
      const resultData = reader.result as string;
      if (resultData) {
        try {
          const importData = JSON.parse(resultData);
          resolve(importData);
        } catch (error) {
          reject(error || "读取数据解析失败");
        }
      } else {
        reject("读取数据解析失败");
      }
    };
  });
};

export const download = () => {
  let debug = {name: '测试name'}
  let str = JSON.stringify(debug)
  let blob: any = new Blob([str], { type: 'application/json' })
  const a = document.createElement('a')
  a.download = 'user.json' // 下载同源的文件
  a.rel = 'noopener'
  a.href = URL.createObjectURL(blob)
  a.dispatchEvent(new MouseEvent('click'))
  URL.revokeObjectURL(blob)
}

/**
 * 获取图片的 base64 编码
 * @param image 图像对象
 * @return {string} 返回已编码的 base64数据
 */
 const getImageBase64 = (image: any) => {
  const canvas = document.createElement('canvas')
  canvas.width = image.width
  canvas.height = image.height
  const ctx = canvas.getContext('2d')
  ctx?.drawImage(image, 0, 0, image.width, image.height)
  // 获取图片后缀名
  const extension = image.src
    .substring(image.src.lastIndexOf('.') + 1)
    .toLowerCase()
  // 某些图片 url 可能没有后缀名，默认是 png
  return canvas.toDataURL('image/' + extension, 1)
}

/**
 * 单张图片下载
 * @param url 图像链接
 * @param downloadName 图片名称
 */
export const downloadImage = (url: string, downloadName: string) => {
  const link = document.createElement('a')
  link.setAttribute('download', downloadName)
  const image = new Image()
  // 添加时间戳，防止浏览器缓存图片
  image.src = url + '?timestamp=' + new Date().getTime()
  // 设置 crossOrigin 属性，解决图片跨域报错
  image.setAttribute('crossOrigin', 'Anonymous')
  image.onload = () => {
    link.href = getImageBase64(image)
    link.click()
  }
}

